package we.core.handlers;

import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import we.caro.CaroExtension;
import we.common.CCommonHandler;
import we.core.bean.CDataContainer;
import we.core.bean.CUser;
import we.database.CDataController;
import we.dispatcher.CDispatcherHandler;
import we.extension.CSystemEvent;
import we.socialcontroller.CSocialUserInfo;
import we.socialcontroller.ISocialController;
import we.socialcontroller.CSocialController;


public class CLoginHandler extends CAbstractCoreHandler {
 //   public static final String SUFFIX_INFO = "_info";
  //  public static final String PREFIX_CARO = "caro_";
    //private final String SUFFIX_GOLD = "_gold";

    @Override
    public int handleEvent(SocketChannel channel, JSONObject data) {
        JSONObject result = new JSONObject();
        CSystemEvent se = null;
        boolean isOk = true;
        try {
            result.put("handler", "login");
            String sessionKey = data.getString("username");
           // Debug.trace(sessionKey);
            String username;
            //username = sessionKey;            
            ISocialController controller = CSocialController.GetController();
            long userId =
                controller.getLoggedInUser(sessionKey);
            CSocialUserInfo userInfo =
                controller.getUserInfo(userId);            
                
            username = userInfo.getUsername();
           // Debug.trace(username);
            
            List<Long> userIdList = controller.getFriendList(sessionKey);
            CCommonHandler.trace(userIdList);
            
            List<CSocialUserInfo> friendList = controller.getUserInfo(userIdList);                    
            CCommonHandler.trace(friendList);
            JSONObject notify = new JSONObject().put("_cmd", "HUL");
            notify.put("params", new JSONObject().put("username", username));
            
            for (CSocialUserInfo info : friendList){
                if (info != null){
                    String name = info.getUsername();
                    CUser user = CDataContainer.instance().getUser(name);
                    if (user != null)
                      CDispatcherHandler.instance().sendResponse(user.channel, notify);        
                }
            }

            if (CDataContainer.instance().getUser(username) == null) {
                // chua login
                CUser u = new CUser();
                u.channel = channel;
                u.username = username;
                u.roomId = -1;
                CDataContainer.instance().addUser(u);
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("eventName", CSystemEvent.SystemEventType.LOGIN);
                params.put("user", u);
                se = new CSystemEvent(this, params);
                result.put("loginOK", 0);

                // them thuoc tinh gold, exp cho user
                if (CDataController.GetController().get(CaroExtension.PREFIX_CARO +
                                                       username +
                                                       CaroExtension.SUFFIX_INFO) == null) {
                    Map<String, Object> info = new HashMap<String, Object>();
                    info.put("gold", 0);
                    info.put("exp", 0);
                    info.put("numWin", 0);
                    info.put("numLose", 0);
                    CDataController.GetController().set(CaroExtension.PREFIX_CARO +
                                                       username + CaroExtension.SUFFIX_INFO,
                                                       info);
                }

                Map<String, Object> info =
                    (HashMap)CDataController.GetController().get(CaroExtension.PREFIX_CARO +
                                                                username +
                                                                CaroExtension.SUFFIX_INFO);

                int gold = (Integer)info.get("gold");
                int exp = (Integer)info.get("exp");
                int numWin = (Integer)info.get("numWin");
                int numLose = (Integer)info.get("numLose");
                
                u.properties.put("exp", String.valueOf(exp));
                u.properties.put("gold", String.valueOf(gold));
                u.properties.put("numWin", String.valueOf(numWin));
                u.properties.put("numLose", String.valueOf(numLose));
                u.properties.put("seesionKey", sessionKey);
                u.properties.put("isBusy", "false");
                u.properties.put("isAutoDeny", "false");
                
                CCommonHandler.trace(u.properties);
            } else {
                // da login roi
                isOk = false;
                result.put("loginOK", 1);
            }
        } catch (JSONException e) {
            CCommonHandler.writeErrLog(e);
            // TODO
            isOk = false;

        } catch (Exception e) {
            CCommonHandler.writeErrLog(e);
            try {
                result.put("loginOK", -1);
            } catch (JSONException f) {
                CCommonHandler.writeErrLog(f);
            }
        }        

        CDispatcherHandler.instance().sendResponse(channel, result);
        if (isOk) {
            dispatchSystemEvent(se);
            return 0;
        }
        return 1;
    }
}
